package com.yanlin.servicepassengeruser.service;

import com.yanlin.internalcommon.dto.ResponseResult;


import com.yanlin.internalcommon.response.UserResponse;
import com.yanlin.internalcommon.dto.PassengerUser;
import com.yanlin.servicepassengeruser.mapper.PassengerUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yanlin.internalcommon.constant.CommonStatusEnum.USER_NOT_EXISTS;

/**
 * <p>标题：UserService</p>
 * <p>功能：</p>
 * <p>
 * 其他说明：
 * </p>
 * <p>审核：</p>
 * <p>重构：</p>
 * <p>创建日期：2025-06-06 06:28</p>
 *
 * @author yanlin
 */
@Service
public class UserService {

    @Autowired
    private PassengerUserMapper passengerUserMapper;

    public ResponseResult loginOrRegister(String passengerPhone) {

        System.out.println("user service 调用，手机号 = " + passengerPhone);
        //根据手机号查询用户信息
        Map<String, Object> map = new HashMap<>();
        map.put("passenger_phone", passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(map);
        //判断用户信息是否存在
        if(passengerUsers.size() == 0){
            LocalDateTime now = LocalDateTime.now();
            PassengerUser user = new PassengerUser();
            user.setPassengerName("庐山");
            user.setPassengerPhone(passengerPhone);
            user.setPassengerGender((byte)0);
            user.setState((byte)0);
            user.setCreateTime(now);
            user.setUpdateTime(now);
            //如果不存在插入信息
            passengerUserMapper.insert(user);
        }

        return ResponseResult.success();
    }

    public ResponseResult getUserByPassengerPhone(String passengerPhone) {
        Map<String, Object> map = new HashMap<>();
        map.put("passenger_phone", passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(map);
        if (passengerUsers.size() == 0) {
            return ResponseResult.fail(USER_NOT_EXISTS.getCode(), USER_NOT_EXISTS.getValue());
        }
        PassengerUser passengerUser = passengerUsers.get(0);
        UserResponse userResponse = new UserResponse();
        userResponse.setPassengerName(passengerUser.getPassengerName());
        userResponse.setProfilePhoto(passengerUser.getProfilePhoto());
        userResponse.setPassengerGender(passengerUser.getPassengerGender());
        userResponse.setPassengerPhone(passengerUser.getPassengerPhone());
        return ResponseResult.success(userResponse);
    }
}